﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QL_LICHLAMVIEC.Models;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace QL_LICHLAMVIEC.Controllers
{
    public class CalendarActionResponseModel
    {
        public String Status;
        public Int64 Source_id;
        public Int64 Target_id;

        public CalendarActionResponseModel(String status, Int64 source_id, Int64 target_id)
        {
            Status = status;
            Source_id = source_id;
            Target_id = target_id;
        }
    }

    public class CalendarController : Controller
    {
        private List<GiangVien> GetDSGV()
        {
            List<GiangVien> giangvien = new List<GiangVien>();

            foreach (var o in new MyEventsDataContext().GIANGVIEN_NHANVIENs)
            {
                var gv = new GiangVien()
                {
                    MSNV = o.MSNV,
                    Checked = false,
                    HoTen = o.Hoten,
                    Chucvu = o.Chuc_vu
                };

                giangvien.Add(gv);
            }

            return giangvien;
        }

        public ActionResult Index()
        {

            ViewData["DSGV"] = GetDSGV();
          //  ViewData["TenLogin"] = Session["UserName"].ToString();
        
           
            return View();
        }
       
       
        public ActionResult PDaoTao() 
        {
           // Session["UserName"] = "";
            return View();
        }

        [HttpPost]
        public ActionResult PDaoTao(HttpPostedFileBase file, FormCollection collection)
        {
            var filename = System.IO.Path.GetFileName(file.FileName);
            string path =HttpContext.Server.MapPath(@"~\Content\Upload\"); // duong dan vat ly
            if (System.IO.File.Exists(path + filename) == true)
            {
                System.IO.File.Delete(path + filename);
            }
            file.SaveAs(path+filename);

            string vpath = HttpContext.Server.MapPath("~/Content/Upload/"); // duong dan ao

            OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +vpath + filename + ";Extended Properties=Excel 8.0");
            try
            {
                OleDbCommand ocmd = new OleDbCommand("select * from [Sheet1$]", oconn);
                oconn.Open();
                OleDbDataReader odr = ocmd.ExecuteReader();
                //  string mstkb = "";
                string So_Phong = "";
                int Tiet = 0;
                int So_Tiet = 0;
                int MSNV = 0;
                string Mon_hoc = "";
                int Tuan_bd = 0;
                int So_tuan = 0;
                DateTime Ngay_dau_tuan;
                DateTime Ngay_cuoi_tuan;
                string Ngay_day = "";


                while (odr.Read())
                {

                   So_Phong = valid(odr, 0);
                    Tiet = int.Parse(valid(odr, 1));
                    So_Tiet = int.Parse(valid(odr, 2));
                    MSNV = int.Parse(valid(odr, 3));
                    Mon_hoc = valid(odr, 4);
                    Tuan_bd = int.Parse(valid(odr, 5));
                    So_tuan = int.Parse(valid(odr, 6));
                    Ngay_dau_tuan = DateTime.Parse(valid(odr, 7));
                    Ngay_cuoi_tuan = DateTime.Parse(valid(odr, 8));
                    Ngay_day = valid(odr, 9);

                    insertdataintosql(Guid.NewGuid().ToString(), So_Phong, Tiet, So_Tiet, MSNV, Mon_hoc, Tuan_bd, So_tuan, Ngay_dau_tuan, Ngay_cuoi_tuan, Ngay_day);
                                 
                }
                oconn.Close();
            }
            catch (DataException ee)
            {
                ViewData["msg"] = ee.Message;
           
            }
            finally
            {
                ViewData["msg"] = "Thời khoá biểu đã nhập vào thành công.";
              
            }


            return View("PDaoTao");
        }
        protected string valid(OleDbDataReader myreader, int stval)//thay the cot rong bang 0
        {

            object val = myreader[stval];
            if (val != DBNull.Value)
                return val.ToString();
            else
                return Convert.ToString(0);
        }

        public void insertdataintosql(string mstbk, string So_Phong, int Tiet, int So_Tiet, int MSNV, string Mon_hoc, int Tuan_bd, int So_tuan,
        DateTime Ngay_dau_tuan, DateTime Ngay_cuoi_tuan, string Ngay_day)
        {
            MyEventsDataContext data = new MyEventsDataContext();
            var TKB = data.SP_THOIKHOABIEU(mstbk, So_Phong, Tiet, So_Tiet, MSNV, Mon_hoc, Tuan_bd, So_tuan, Ngay_dau_tuan, Ngay_cuoi_tuan, Ngay_day);
            data.SubmitChanges();

            
        }

        public ActionResult Login()
        {
         //   Session["UserName"] = "";
            return View();
        }

        [HttpPost]
        public ActionResult Login(FormCollection collection)
        {
            MyEventsDataContext data = new MyEventsDataContext();

            string login = collection["login"];
            string msnv = "";
            if (login == "GV" || login == "BCN" || login == "admin" || login == "PDT")
            {
                string user = collection["User"];
                string pass = collection["Pass"];
                var lg = from u in data.USERs
                         where u.Username == user && u.Password == pass
                        select u;

                List<USER> List_User = lg.ToList();
       
                if (List_User.Count == 0)
                {
                    ViewData["msg"] = "Sai Tài khoản hoặc mật khẩu.";
                    return View("Login");
                }
                msnv = List_User[0].MSNV.ToString();
                Session["UserName"] =  List_User[0].Username.ToString();
            }

           
            switch (login)
            {
                default:
                    Session["Disable"] = 0;
                    Session["GIAO_VIEN"] = 0;
                    Session["CHIA_SE"] = true;
                    Session["TRUONG_KHOA"] = false;
                    Session["GV"] = 0;

                     Session["LOAI"] = "SV";
                                       
                    break;
                case "GV":
                    Session["Disable"] = 1;
                    Session["GIAO_VIEN"] = msnv;
                    Session["CHIA_SE"] = false;
                    Session["TRUONG_KHOA"] = false;
                    ///////
                    Session["GV"] = 1;
                    Session["msnv"] = msnv;

                    Session["LOAI"] = "GV";
                    break;
                case "BCN":
                    Session["Disable"] = 1;
                    Session["GIAO_VIEN"] = msnv;
                    Session["CHIA_SE"] = true;
                    Session["TRUONG_KHOA"] = true;
                    Session["GV"] = 0;
                    Session["LOAI"] = "BCN";
                    break;
                case "admin":
                    return RedirectToAction("Index","Admin");
                case "PDT":
                    return RedirectToAction("Index","PDaoTao");
                   
            }
            return RedirectToAction("Index");
        }

        public ActionResult Data()
        {
           
         //   int msnv = Convert.ToInt32(Session["GIAo_VIEN"]);
            
          //  bool truongkhoa = Convert.ToBoolean(Session["TRUONG_KHOA"]);
            //var sukien = from s in data.SU_KIENs
            //             where (s.MSNV == msnv || truongkhoa == true)
            //                && (s.Chia_se == chiase || chiase == false)
            //             select s;
            MyEventsDataContext data = new MyEventsDataContext();
            bool chiase = Convert.ToBoolean(Session["CHIA_SE"]);
            IQueryable sukien = null;
            if (Session["LOAI"].ToString() == "GV")
            {
                sukien = from s in data.SU_KIENs
                         where s.MSNV == int.Parse(Session["msnv"].ToString())
                         select s;
            }
            else
            {
                sukien = from s in data.SU_KIENs
                         where s.Chia_se == chiase  
                         select s;
            }
           

            return View(sukien);
        }

        [HttpPost]
        public ActionResult LoadData()
        {
            MyEventsDataContext data = new MyEventsDataContext();
            IQueryable gv=null;
            if (Session["GV"].ToString() == "1")
            {
                gv = from n in data.GIANGVIEN_NHANVIENs
                     where n.MSNV == int.Parse(Session["msnv"].ToString())
                     select new { n.MSNV, n.Hoten };
            }
            else
            {
                gv = from n in data.GIANGVIEN_NHANVIENs
                     where !n.Chuc_vu.Equals("Admin")
                                   select new { n.MSNV, n.Hoten };
            }
            return Json((IQueryable)gv, JsonRequestBehavior.AllowGet);
            //return Json(from n in data.GIANGVIEN_NHANVIENs select new {n.MSNV, n.Hoten}, JsonRequestBehavior.AllowGet);
        }

         [HttpPost]
        public ActionResult Save(FormCollection actionValues)
        {
            String action_type = actionValues["!nativeeditor_status"];
            Int64 source_id = Int64.Parse(actionValues["id"]);
            Int64 target_id = source_id;

            MyEventsDataContext data = new MyEventsDataContext();
            SU_KIEN changedEvent;
        //    try
         //   {
         //   string login = collection["login"];
            if(Session["Disable"].ToString() =="0")
            {
                action_type = "out";
            }
            switch (action_type)
                {
                    case "inserted":
                        changedEvent = new SU_KIEN();
                        changedEvent.Ngay_bat_dau = DateTime.Parse(actionValues["start_date"]);
                        changedEvent.Ngay_ket_thuc = DateTime.Parse(actionValues["end_date"]);
                        changedEvent.Noi_dung = actionValues["text"];
                        changedEvent.MSNV = Convert.ToInt32(Session["GIAo_VIEN"]);
                        changedEvent.Chia_se = Convert.ToBoolean(Session["CHIA_SE"]);
                        changedEvent.Loai_su_kien = 1;

                        if (changedEvent.Loai_lap == null)
                        {
                            changedEvent.Loai_lap = "";
                            changedEvent.Ket_thuc_sk = 0;
                            changedEvent.Do_dai = 0;
                        }
                        else
                        {

                            changedEvent.Loai_lap = actionValues["rec_type"];
                            changedEvent.Ket_thuc_sk = int.Parse(actionValues["event_pid"]);
                            changedEvent.Do_dai = int.Parse(actionValues["event_length"]);
                        }
                        data.SU_KIENs.InsertOnSubmit(changedEvent);
                        break;
                    case "deleted":
                        changedEvent = data.SU_KIENs.SingleOrDefault(ev => ev.MSSK == source_id);
                        data.SU_KIENs.DeleteOnSubmit(changedEvent);
                        break;
                    case "out":
                        changedEvent = data.SU_KIENs.SingleOrDefault(ev => ev.MSSK == source_id);
                        break;
                    default: // "updated"
                        changedEvent = data.SU_KIENs.SingleOrDefault(ev => ev.MSSK == source_id);
                        changedEvent.Ngay_bat_dau = DateTime.Parse(actionValues["start_date"]);
                        changedEvent.Ngay_ket_thuc = DateTime.Parse(actionValues["end_date"]);
                        changedEvent.Noi_dung = actionValues["text"];
                        if (changedEvent.Loai_lap == null)
                        {
                            changedEvent.Loai_lap = "";
                            changedEvent.Ket_thuc_sk = 0;
                            changedEvent.Do_dai = 0;
                        }
                        else
                        {

                            changedEvent.Loai_lap = actionValues["rec_type"];
                            if (actionValues["event_pid"] == null)
                            {
                                actionValues["event_pid"] = "0";
                                actionValues["event_length"] = "0";
                            }
                            changedEvent.Ket_thuc_sk = int.Parse(actionValues["event_pid"]);
                            changedEvent.Do_dai = int.Parse(actionValues["event_length"]);
                        }
                        // UpdateModel(changedEvent);
                        break;
               }
            if (changedEvent != null)
            {
                data.SubmitChanges();
                target_id = changedEvent.MSSK;
            }
            //}
            //catch
            //{
            //    action_type = "error";
            //}

            return View(new CalendarActionResponseModel(action_type, source_id, target_id));
        }

        [HttpPost]
        public ActionResult Index(FormCollection collection)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    MyEventsDataContext context = new MyEventsDataContext();

                    DateTime startdate = Convert.ToDateTime(collection["Ngay_bat_dau"]);
                    DateTime enddate = Convert.ToDateTime(collection["Ngay_ket_thuc"]);
                    bool shared = Convert.ToBoolean(collection["Chia_se"].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)[0]);
                    string content = collection["Noi_dung"];
                    string[] ids = collection["Nguoi_tham_gia"].Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    if (ids.Length != 0)
                    {
                        foreach (string s in ids)
                        {
                            SU_KIEN sk = new SU_KIEN()
                            {
                                Ngay_bat_dau = startdate,
                                Ngay_ket_thuc = enddate,
                                Ket_thuc_sk = 0,
                                Loai_lap = "",
                                Loai_su_kien = 1,
                                Do_dai = 0,
                                Noi_dung = content,
                                Chia_se = shared,
                                MSNV = Convert.ToInt32(s)
                            };

                            context.SU_KIENs.InsertOnSubmit(sk);
                        }

                        context.SubmitChanges();
                        
                        return RedirectToAction("Index");
                       
                    }
                }
                catch
                {
                }
            }

            ViewData["DSGV"] = GetDSGV();
            ViewData["TenLogin"] = Session["UserName"].ToString();
            return View();
        }
    }
}
